import paho.mqtt.publish as publish
from paho.mqtt import client
from paho import mqtt
import time


# MQTT配置
MQTTUSERNAME = 'root'
MQTTPASSWORD = 'emdoor'
MQTTSUBTOPIC = 'lorawan/uplink'
MQTTPORT = 1883
MQTTHOST = '39.108.232.60'


def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    client.subscribe("test")  #订阅主题

def on_message(client, userdata, msg):

    print(msg.topic+" "+msg.payload.decode("utf-8"))

if __name__ == '__main__':
    mqtt_client = client.Client(client_id="{}".format(time.time()),  #客户端必须唯一
                               clean_session=True, userdata=None,
                               protocol=client.MQTTv31)
    userdata = {'hello':'world'}
    mqtt_client.user_data_set(userdata)  #设置client user_date信息
    mqtt_client.username_pw_set(MQTTUSERNAME, MQTTPASSWORD) # 必须设置，否则会返回「Connected with result code 4」
    mqtt_client.on_connect = on_connect
    mqtt_client.on_message = on_message
    mqtt_client.connect(MQTTHOST, MQTTPORT, 60)
    while 1:
        mqtt_client.publish("test", "你好 MQTT", qos=0, retain=False) # 发布消息
        time.sleep(10)

    # publish.single("test", "你好 MQTT", qos = 1,hostname=MQTTHOST,port=MQTTPORT, client_id="{}".format(time.time()),auth = {'username':MQTTUSERNAME ,'password':MQTTPASSWORD}) #发送完之后断开连接